package cn.com.gzheroli.bfw.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Service;
import cn.com.gzheroli.bfw.mapper.system.TerritoryMapper;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSTerritory;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.service.bfw.TerritoryService;

@Service("territoryService")
public class TerritoryServiceImpl  implements TerritoryService{

	@Resource
	private SystemService systemService;
	@Resource
	private TerritoryMapper territoryMapper;
	@Resource
	private CommonService commonService;
	public List<Map> getTerritoryList(Map dataMap) {
		return territoryMapper.getTerritoryList(dataMap);
	}
	
	public TSTerritory getTerritory(String id){
		String sql="select t.*,p.TERRITORY_NAME parentName,p.TERRITORY_LEVEL pTerritoryLevel  from t_s_territory t left join  t_s_territory p on p.id=t.PARENT_ID where t.id=#{id}";
		Map para=new HashMap();
		para.put("id", id);
		TSTerritory t=commonService.findOneObjForJdbc(sql, para, TSTerritory.class);
		return t;
	}
	public List<Map> setPTerritory(String parentId){
		Map para=new HashMap();
		para.put("pid", parentId);
		List<Map> terList=territoryMapper.getTerritoryList(para);
		return terList;
	}
	public  void updateAreaLevelNoCased(String pid,String plevelNo) {
		Map para=new HashMap();
		para.put("pid", pid);
		/*SQL sql=new SQL();
		sql.SELECT("*");
		sql.FROM("t_s_territory");*/
		String sql="select * from t_s_territory where 1=1 ";
		if(pid==null||pid.trim().equals(""))
			sql=sql+" and (PARENT_ID is null or PARENT_ID='')";
		else
			sql=sql+" and PARENT_ID=#{pid}";
		List<TSTerritory> areas=commonService.findByQueryString(sql, TSTerritory.class, para);
		for(int i=0;i<areas.size();i++){
			TSTerritory area=areas.get(i);
			DecimalFormat df = new DecimalFormat("000");
			String newLevelNo=plevelNo+df.format(i+1);
			area.setLevelNo(newLevelNo);
			commonService.executeSQL("update t_s_territory set LEVEL_NO='"+newLevelNo+"' where ID='"+area.getId()+"'");
			updateAreaLevelNoCased(area.getId(),newLevelNo);
		}
		
    }

}
